package com.link_with_health.service.impl;

import com.link_with_health.common.VerifyUserUtil;
import com.link_with_health.exception.BaseException;
import com.link_with_health.exception.ModifyDatabaseFailedException;
import com.link_with_health.exception.NullQueryResultException;
import com.link_with_health.mapper.InquiryMapper;
import com.link_with_health.mapper.PatientMapper;
import com.link_with_health.mapper.PrescriptionMapper;
import com.link_with_health.mapper.UserMapper;
import com.link_with_health.model.PatientEntity;
import com.link_with_health.model.UserEntity;
import com.link_with_health.service.BaseService;
import com.link_with_health.service.PatientService;
import com.link_with_health.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("patientService")
public class PatientServiceImpl extends BaseService implements PatientService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    PatientMapper patientMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    InquiryMapper inquiryMapper;

    @Resource(name = "userService")
    UserService userService;

    /**
     * 通过患者id获取患者信息
     * @param patientId 患者id
     * @return  患者信息
     * @throws BaseException 异常
     */
    @Override
    public PatientEntity getPatientByPatientId(Long patientId) throws BaseException {
        PatientEntity entity = null;
        try {
            entity = patientMapper.queryPatientByPatientId(patientId);
        } catch(Exception e) {
            logger.error("[query patient failed]",e);
        }
        if (entity == null)
            throw new NullQueryResultException("PATIENT.PATIENT_ID: "+patientId);
        return entity;
    }

    /**
     * 通过用户id获取患者信息
     * @param userId 用户id
     * @return  患者信息
     * @throws BaseException 异常
     */
    @Override
    public List<PatientEntity> getPatientByUserId(Long userId) throws BaseException {
        List<PatientEntity> patientList = null;
        try {
            patientList = patientMapper.queryPatientByUserId(userId);

            patientList = VerifyUserUtil.patientFilter(patientList);

        } catch (Exception e) {
            logger.error("[query patient failed]",e);
        }

        if (patientList == null || patientList.isEmpty())
            throw new NullQueryResultException("PATIENT.USER_BIND: "+userId);

        return patientList;
    }

    /**
     * 通过用户名字换取患者信息 支持模糊查询
     * @param username 用户名
     * @return  患者信息
     * @throws BaseException 异常
     */
    @Override
    public List<PatientEntity> getPatientByUserName(String username) throws BaseException {
        List<PatientEntity> patientList = null;
        try {
            patientList = patientMapper.queryPatientByUserName("%"+username+"%");

            patientList = VerifyUserUtil.patientFilter(patientList);

        } catch (Exception e) {
            logger.error("[query patient failed]",e);
        }
        if(patientList == null || patientList.isEmpty())
            throw new NullQueryResultException("PATIENT USER.USER_NAME: "+username);
        return patientList;
    }

    /**
     * 通过真实姓名获取患者信息 支持模糊查询
     * @param realName  真实姓名
     * @return  患者信息
     * @throws BaseException 异常
     */
    @Override
    public List<PatientEntity> getPatientByRealName(String realName) throws BaseException {
        List<PatientEntity> patientList = null;
        try {
            patientList = patientMapper.queryPatientByRealName("%"+realName+"%");

            patientList = VerifyUserUtil.patientFilter(patientList);

        } catch (Exception e) {
            logger.error("[query patient failed]",e);
        }
        if (patientList == null || patientList.isEmpty())
            throw new NullQueryResultException("PATIENT.REAL_NAME: "+realName);

        return patientList;
    }

    /**
     * 获取所有患者信息
     * @return  患者信息
     * @throws BaseException 异常
     */
    @Override
    public List<PatientEntity> getAllPatient() throws BaseException {
        List<PatientEntity> patientList = null;
        try {
            patientList = patientMapper.queryAllPatient();

            patientList = VerifyUserUtil.patientFilter(patientList);

        } catch (Exception e) {
            logger.error("[query patient failed]",e);
        }
        if (patientList == null || patientList.isEmpty())
            throw new NullQueryResultException("ALL PATIENT");

        return patientList;
    }

    /**
     * 添加患者信息
     * @param patient 患者信息
     * @return  改动数量
     * @throws BaseException 异常
     */
    @Override
    public int addPatient(PatientEntity patient) throws BaseException {
        int result = 0;

        //校验是否为合法绑定用户
        Long userBind = patient.getUserBind();
        UserEntity user = userService.getUserByUserId(userBind);
        //判断是否为可操控用户
        if(!VerifyUserUtil.verifyUserStatus(user))
            throw new NullQueryResultException("[user status is invalid]");

        try {
            result = patientMapper.insertPatient(patient);
        } catch (Exception e) {
            logger.error("[add patient failed]",e);
        }
        if (result == 0)
            throw new ModifyDatabaseFailedException("INSERT PATIENT: "+patient);

        return result;
    }

    /**
     * 修改患者信息
     * @param patient 患者信息
     * @return 改动数量
     * @throws BaseException 异常
     */
    @Override
    public int changePatient(PatientEntity patient) throws BaseException {
        int result = 0;

        //校验是否为合法绑定用户
        Long userBind = patient.getUserBind();
        UserEntity user = userService.getUserByUserId(userBind);
        //判断是否为可操控用户
        if(!VerifyUserUtil.verifyUserStatus(user))
            throw new NullQueryResultException("[user status is invalid]");


        try {
            result = patientMapper.updatePatient(patient);
        } catch (Exception e) {
            logger.error("[change patient failed]",e);
        }

        if (result == 0)
            throw new ModifyDatabaseFailedException("UPDATE PATIENT: "+patient);
        return result;
    }

    /**
     * 删除患者信息
     * @param patientId 患者id
     * @return  改动数量
     * @throws BaseException 异常
     */
    @Override
    public int deletePatient(Long patientId) throws BaseException {
        int result = 0;
        try {
            if(inquiryMapper.queryInquiryByPatientId(patientId).isEmpty())
                result = patientMapper.deletePatient(patientId);
        } catch (Exception e) {
            logger.error("[delete Patient failed]",e);
        }
        if (result == 0)
            throw new ModifyDatabaseFailedException("DELETE PATIENT.PATIENT_ID: "+patientId);
        return result;
    }
}
